package cn.edu.hit.core.transfer;

import cn.edu.hit.fft.Complex;
import cn.edu.hit.core.Document;

import java.util.*;
import java.util.stream.Collectors;

import static cn.edu.hit.fft.FFTJ.fft;
import static cn.edu.hit.core.combine.CombineAdapter.TRANSFER_ARG;

public class FFTTransfer extends HistoryTransfer {
    @Override
    public boolean accept(String name) {
//        System.out.println("fft test "+ name);
        return "fft".equalsIgnoreCase(name);
    }

    @Override
    public List transfer(List rawsource, Document configure) {
        List source = super.transfer(rawsource, configure);
        System.out.println(source);
        String transferArg = configure.getString(TRANSFER_ARG);

        int poolSize = getDefaultPoolSize();
        try {
            poolSize = Integer.parseInt(transferArg);
        } catch (Exception e) {
            e.printStackTrace();
        }

        poolSize = poolSize < getDefaultPoolSize() ? getDefaultPoolSize() : poolSize;

        if (source.size() < poolSize) {
            return Collections.emptyList();
        }

        Complex[] input = source.stream().mapToDouble(x -> {
            if (x instanceof Number) {
                return ((Number) x).doubleValue();
            } else if (x instanceof String) {
                try {
                    return Double.parseDouble(x.toString());
                } catch (Exception e) {
                }
            }
            return 0;
        }).boxed().map(real -> new Complex(real, 0)).toArray(Complex[]::new);

        double[] result = fft(input);
        System.out.println(Arrays.toString(result));
        return Arrays.stream(result).boxed().collect(Collectors.toList());
    }

    @Override
    protected int getDefaultPoolSize() {
        return 512;
    }
}
